<template>
  <a-upload
      :action="uploadUrl"
      v-model:file-list="fileList"
      accept=".pdf"
      :headers="headers"
      :maxCount="maxCount"
      @change="handleChange"
      @remove="handleRemove"
  >
    <a-button size="small" :loading="loading" type="primary" v-if="!isMaxCount">
      <upload-outlined></upload-outlined>
      上传文件
    </a-button>
  </a-upload>
</template>

<script lang="ts" setup>
import {ref, computed, watchEffect} from 'vue';
import {getFileAccessHttpUrl, getHeaders} from '@/utils/compUtils';
import {message} from 'ant-design-vue';
import {uploadUrl} from '@/api/common/api'
import { UploadOutlined } from '@ant-design/icons-vue';

const emit = defineEmits(["change"]);
const fileList = ref<any>([])

const headers = getHeaders();
const loading = ref<boolean>(false)
const props = defineProps({
  fileId: {
    type: String,
  },
  maxCount: {
    type: Number,
    default: 1
  }
})

watchEffect(() => {
  if (props.fileId) {
    fileList.value = []
    fileList.value.push({
      url: getFileAccessHttpUrl(props.fileId),
      name: props.fileId.substring(props.fileId.lastIndexOf("/") + 1, props.fileId.lastIndexOf("_"))
          + props.fileId.substring(props.fileId.lastIndexOf("."))
    })
  }
})

// 是否达到了最大上传数量
const isMaxCount = computed(() => props.maxCount > 0 && fileList.value.length >= props.maxCount);

function handleRemove(file) {
  fileList.value = fileList.value.filter(item => item.url != file.url)
  emit('change', null)
}

const handleChange = (info: any) => {
  if (info.file.status !== 'uploading') {
  }
  if (info.file.status === 'done') {
    info.file.url = getFileAccessHttpUrl(info.file.response.result);
    emit('change', info.file.response.result)
  } else if (info.file.status === 'error') {
  }
};
</script>
<style lang="css" scoped>
video {
  width: 600px;
  height: 400px;
  object-fit: cover;
  border: 1px solid black;
}
</style>
